import os, sys, optparse, ConfigParser, logging
import hanzoweb

logger = logging.root
logger.addHandler(logging.StreamHandler())

def setup_optionparser():
   usage = "usage: %prog [options] url"
   parser = optparse.OptionParser(usage)
   parser.add_option("-c", "--config", dest="configfile", help="path to config file containing username & api key")
   parser.add_option("-v", "--verbose", action="store_true", dest="verbose")
   parser.add_option("-q", "--quiet", action="store_true", dest="quiet")
   parser.add_option("-n", "--name", dest="name", help="a name/title of the site")
   parser.add_option("-t", "--tags", dest="tags", help="tags to associate with the content")   
   parser.add_option("-d", "--description", dest="description", help="short plaintext comment(s) or note(s)")
   parser.add_option("-k", "--kind", dest="scope", help="resource type; 'bookmark', 'page', 'context' or 'website'")
   parser.add_option("-p", "--public", action="store_true", dest="public", help="allow anyone to see archived content")
   parser.add_option("-s", "--secret", action="store_false", dest="public", help="keep the resource private")
   
   return parser


if __name__=="__main__":
   cmd_parser = setup_optionparser()
   (options, args) = cmd_parser.parse_args()

   if options.verbose:
      logger.setLevel(logging.DEBUG)

   if len(args) == 0:
      cmd_parser.error("no url given")
   config = ConfigParser.ConfigParser()
   filename = getattr(options, "config", None) or "gather.ini"
   config_path = os.getcwd() + sys.argv[0][1:-len(filename)] + os.sep + filename
   logging.debug("using config from %s" % config_path)   
   try:
      config.readfp(open(config_path))
      username, apikey = [item[1] for item in config.items("authentication")]
   except:
      sys.exit("cannot find config file with username & api key at %s" % config_path)
   
   tags = getattr(options, "tags") or None
   name = getattr(options, "name") or None
   descr = getattr(options, "description") or None
   scope = getattr(options, "scope") or None
   visibility = "public" if getattr(options, "public", None) else "private"
   
   logger.info("archiving %s" % args[0])
   status, id = hanzoweb.send_request(args[0], username, apikey, tags, name, descr, scope, visibility)
   logger.info("result: %s, id: %s" % (status, id))
